import {ChangeDetectorRef, Component} from '@angular/core';
import {ActionSheetController, AlertController, NavController, NavParams} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {HttpService} from '../../../providers/http.service';
import {CommonFunc} from '../../../providers/commonFunc';
import {appConfig} from '../../../providers/config';
import {Camera, CameraOptions} from '@ionic-native/camera';
import {FileTransfer, FileTransferObject, FileUploadOptions} from '@ionic-native/file-transfer';
import {PhotoViewer} from '@ionic-native/photo-viewer';
import {maintUserAdded} from "../../maint-user-add/bean/maintUserAdded.bean";
import {TractionPage} from "../traction/traction";
import {HydpressPage} from "../hydpress/hydpress";
import {DebrisPage} from "../debris/debris";
import {EscalatorPage} from "../escalator/escalator";


@Component({
    templateUrl: 'maintenanceBefore.html',
    providers: [HttpService, CommonFunc]
})
export class maintenanceBeforePage {
    appConfig = appConfig
    itemlist = [];
    xcfhcsList = [];
    ldbhList = [];
    elevatorPlace: any;
    otherPlace: any;
    placeType: any;
    oldplaceType: any;
    oldelevatorPlace: any;
    elevatorInfo: any;
    elevatorNum: any;
    user: any;
    workType: string;
    isPassenger: boolean = false; //是否是乘客
    elevatorType: string;

    constructor(
        public navCtrl: NavController,
        private storage: Storage,
        private httpService: HttpService,
        private alert: AlertController,
        private camera: Camera,
        private commonFunc: CommonFunc,
        private transfer: FileTransfer,
        private photoViewer: PhotoViewer,
        private actionSheet: ActionSheetController,
        public cd: ChangeDetectorRef,
        private navParams: NavParams,
    ) {
        this.storage.get('user').then(data => {
            this.user = data;
        })
        this.elevatorInfo = this.navParams.get('elevatorInfo');
        this.workType = this.navParams.get("type");
        this.isPassenger = this.navParams.get("isPassenger");
        this.elevatorType = this.navParams.get("ElevaType");
        this.elevatorNum = this.navParams.get("elevatorNum");
        this.oldplaceType = this.elevatorInfo.placeType;
        this.placeType = this.elevatorInfo.placeType;
        this.oldelevatorPlace = this.elevatorInfo.elevatorPlace;

        this.storage.get(this.elevatorNum + "safeImg").then(data =>{
            if(data != null){
                this.xcfhcsList = data.xcfhcs;
                this.ldbhList = data.ldbh;
            }
        })

        if (this.elevatorInfo.placeType == 0) {
             this.otherPlace = this.elevatorInfo.elevatorPlace;
         }
         if (this.elevatorInfo.placeType == 1) {
             this.elevatorPlace = this.elevatorInfo.elevatorPlace;
         }

        if (this.navParams.get('isLook')) {
            let elevatorType = this.navParams.get('ElevaType');
            let elevatorNum = this.navParams.get('elevatorNum');
            //this.elevatorNum = this.navParams.get('elevatorNum');
            if (elevatorType == '4' || elevatorType == '6') {
                this.storage.get(elevatorNum + 'escalator-half-mon').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
            if (elevatorType == '3') {
                this.storage.get(elevatorNum + 'debirs-half').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
            if (elevatorType == '2') {
                this.storage.get(elevatorNum + 'hydpress-half').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
            if (elevatorType == '1' || elevatorType == '5') {
                this.storage.get(elevatorNum + 'traction-half').then(data => {
                    if (data == null) {
                        return;
                    }
                    if (data.xcfhcs) {
                        this.xcfhcsList = data.xcfhcs.split(',');
                    }
                    if (data.ldbh) {
                        this.ldbhList = data.ldbh.split(',');
                    }
                    if (data.maintUserAddedList && data.maintUserAddedList.length > 0) {
                        data.maintUserAddedList.forEach(element => {
                            let maintUserAddedBean: maintUserAdded = new maintUserAdded();
                            maintUserAddedBean.maintContent = element.maintContent;
                            maintUserAddedBean.result = JSON.parse(element.result);
                            maintUserAddedBean.result.picUrl = maintUserAddedBean.result.picUrl.split(',')
                            this.itemlist.push(maintUserAddedBean);
                        });
                    }
                });
            }
        }
    }

    changePlace(type) {
        if (type == 1) {
            this.otherPlace = null;
        } else {
            this.elevatorPlace = null;
        }
    }

    doSubmit() {

         if (this.navParams.get('isLook')) {
             let toas = this.commonFunc.showInsideErrorToast({
                 errorMessage: '已提交维保记录不能修改'
             });
             toas.present();
             return;
         }

        /**
         * 缓存安全措施照片
         */
        this.storage.set(this.elevatorNum + "safeImg",{
            "xcfhcs": this.xcfhcsList,
            "ldbh": this.ldbhList
        })

        if (!this.placeType || (!this.otherPlace && !this.elevatorPlace)) {
            let toas = this.commonFunc.showInsideErrorToast({
                errorMessage: '电梯所在场所不能为空'
            });
            toas.present();
            return;
        }
        if (this.placeType == 0) {
            this.elevatorPlace = this.otherPlace;
        }
        if (this.oldplaceType != this.placeType ||
            this.oldelevatorPlace != this.elevatorPlace) {
            let param = {
                id: this.elevatorInfo.id,
                placeType: this.placeType,
                elevatorPlace: this.elevatorPlace
            }
            this.httpService.updateElevatorPlace(param).subscribe(data => {
                console.log(JSON.stringify(data));
            });
        }

        let date = new Date().getTime();
        if (this.elevatorType == "1" || this.elevatorType == "5") {
            //工曳电梯
            this.navCtrl.push(TractionPage, {
                ElevaType: this.elevatorType,
                type: this.workType,
                elevatorNum: this.elevatorNum,
                elevatorInfo: this.elevatorInfo,
                date: date,
                xcfhcs: this.xcfhcsList,
                ldbh: this.ldbhList,
            }); //跳转 （月--年）保
        }
        if (this.elevatorType == "2") {
            //液压
            this.navCtrl.push(HydpressPage, {
                ElevaType: this.elevatorType,
                type: this.workType,
                elevatorNum: this.elevatorNum,
                elevatorInfo: this.elevatorInfo,
                date: date,
                xcfhcs: this.xcfhcsList,
                ldbh: this.ldbhList,
            }); //跳转 （月--年）保
        }
        if (this.elevatorType == "3") {
            //杂物
            this.navCtrl.push(DebrisPage, {
                ElevaType: this.elevatorType,
                type: this.workType,
                elevatorNum: this.elevatorNum,
                elevatorInfo: this.elevatorInfo,
                date: date,
                xcfhcs: this.xcfhcsList,
                ldbh: this.ldbhList,
            }); //跳转 （月--年）保
        }
        if (this.elevatorType == "4" || this.elevatorType == "6") {
            //自动扶梯
            this.navCtrl.push(EscalatorPage, {
                ElevaType: this.elevatorType,
                type: this.workType,
                elevatorNum: this.elevatorNum,
                elevatorInfo: this.elevatorInfo,
                date: date,
                xcfhcs: this.xcfhcsList,
                ldbh: this.ldbhList,
            }); //跳转 （月--年）保
        }
    }

    presentActionSheet(i) {
        let buttonList: any = [];
        buttonList.push({
            text: '拍照',
            role: '拍照',
            handler: () => {
                let options: CameraOptions = {
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        if (!this.commonFunc.hasNetWork()) {
                            if (i == 'c') {
                                this.xcfhcsList.push(imageData);
                            } else {
                                this.xcfhcsList[i] = imageData;
                            }
                            return;
                        }
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
                        options.fileKey = 'file';
                        options.fileName = 'test.jpg';
                        options.mimeType = 'image/jpeg';
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul['response']);
                            if (aa['status'] == 200) {
                                if (aa['data'].length > 0) {
                                    if (i == 'c') {
                                        this.xcfhcsList.push(aa['data']);
                                    } else {
                                        this.xcfhcsList[i] = aa['data'];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });
        buttonList.push({
            text: '从相册选择照片',
            role: '从相册选择照片',
            handler: () => {
                let options: CameraOptions = {
                    sourceType: 0,
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        if (!this.commonFunc.hasNetWork()) {
                            if (i == 'c') {
                                this.xcfhcsList.push(imageData);
                            } else {
                                this.xcfhcsList[i] = imageData;
                            }
                            return;
                        }
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        options.fileKey = 'file';
                        options.fileName = 'test.jpg';
                        options.mimeType = 'image/jpeg';
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul['response']);
                            if (aa['status'] == 200) {
                                if (aa['data'].length > 0) {
                                    if (i == 'c') {
                                        this.xcfhcsList.push(aa['data']);
                                    } else {
                                        this.xcfhcsList[i] = aa['data'];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });

        buttonList.push({
            text: '取消',
            role: '取消',
            handler: () => {
            }
        });

        let actionSheet = this.actionSheet.create({buttons: buttonList});
        actionSheet.present();
    }

    onHold2(param) {
        let actionSheet = this.actionSheet.create({
            buttons: [
                {
                    text: '重拍',
                    role: '重拍',
                    handler: () => {
                        let i = this.xcfhcsList.indexOf(param);
                        this.presentActionSheet(i);
                    }
                },
                {
                    text: '查看大图',
                    role: '查看大图',
                    handler: () => {
                        let url: string = param;
                        this.photoViewer.show(
                            encodeURI(
                                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
                            ).replace('%5C', '/'),
                            null,
                            {share: false}
                        );
                    }
                },
                {
                    text: '删除',
                    handler: () => {
                        let i = this.xcfhcsList.indexOf(param);
                        this.xcfhcsList.splice(i, 1);
                    }
                },
                {
                    text: '取消',
                    role: '取消',
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }

    presentActionSheet1(i) {
        let buttonList: any = [];
        buttonList.push({
            text: '拍照',
            role: '拍照',
            handler: () => {
                let options: CameraOptions = {
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        if (!this.commonFunc.hasNetWork()) {
                            if (i == 'c') {
                                this.ldbhList.push(imageData);
                            } else {
                                this.ldbhList[i] = imageData;
                            }
                            return;
                        }
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
                        options.fileKey = 'file';
                        options.fileName = 'test.jpg';
                        options.mimeType = 'image/jpeg';
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul['response']);
                            if (aa['status'] == 200) {
                                if (aa['data'].length > 0) {
                                    if (i == 'c') {
                                        this.ldbhList.push(aa['data']);
                                    } else {
                                        this.ldbhList[i] = aa['data'];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });
        buttonList.push({
            text: '从相册选择照片',
            role: '从相册选择照片',
            handler: () => {
                let options: CameraOptions = {
                    sourceType: 0,
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        if (!this.commonFunc.hasNetWork()) {
                            if (i == 'c') {
                                this.ldbhList.push(imageData);
                            } else {
                                this.ldbhList[i] = imageData;
                            }
                            return;
                        }
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        options.fileKey = 'file';
                        options.fileName = 'test.jpg';
                        options.mimeType = 'image/jpeg';
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul['response']);
                            if (aa['status'] == 200) {
                                if (aa['data'].length > 0) {
                                    if (i == 'c') {
                                        this.ldbhList.push(aa['data']);
                                    } else {
                                        this.ldbhList[i] = aa['data'];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });

        buttonList.push({
            text: '取消',
            role: '取消',
            handler: () => {
            }
        });

        let actionSheet = this.actionSheet.create({buttons: buttonList});
        actionSheet.present();
    }

    onHold3(param) {
        let actionSheet = this.actionSheet.create({
            buttons: [
                {
                    text: '重拍',
                    role: '重拍',
                    handler: () => {
                        let i = this.ldbhList.indexOf(param);
                        this.presentActionSheet(i);
                    }
                },
                {
                    text: '查看大图',
                    role: '查看大图',
                    handler: () => {
                        let url: string = param;
                        this.photoViewer.show(
                            encodeURI(
                                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
                            ).replace('%5C', '/'),
                            null,
                            {share: false}
                        );
                    }
                },
                {
                    text: '删除',
                    handler: () => {
                        let i = this.ldbhList.indexOf(param);
                        this.ldbhList.splice(i, 1);
                    }
                },
                {
                    text: '取消',
                    role: '取消',
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }
}